package com.parleys.android.client.ui;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.Html;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;

import com.parleys.android.client.R;
import com.parleys.android.client.provider.ParleysContract.News;
import com.parleys.android.client.util.NotifyingAsyncQueryHandler;
import com.parleys.android.client.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.parleys.android.client.util.UIUtils;

public class NewsDetailActivity extends Activity implements AsyncQueryListener {
	
	private static final String TAG = "NewsDetailActivity";
	
	private Uri mNewsUri;
	private NotifyingAsyncQueryHandler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
        setContentView(R.layout.activity_news_detail);

        final Intent intent = getIntent();
        mNewsUri = intent.getData();

        mHandler = new NotifyingAsyncQueryHandler(this, this);
        startQuery();
        markRead();
	}

	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}

	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		try {
	        if (!cursor.moveToFirst()) return;
	        final String title = cursor.getString(NewsQuery.TITLE);
			final String item = cursor.getString(NewsQuery.ITEM);
			final long createdOn = cursor.getLong(NewsQuery.CREATED_ON);
			
			final TextView titleView = (TextView) findViewById(R.id.news_title); 
			final TextView dateView = (TextView) findViewById(R.id.news_date); 
			final TextView itemView = (TextView) findViewById(R.id.news_item); 
			
			titleView.setText(title);
			dateView.setText(DateUtils.getRelativeTimeSpanString(createdOn));
			itemView.setText(Html.fromHtml(item));
			itemView.setMovementMethod(new LinkMovementMethod());
		} finally {
			cursor.close();
		}
	}
	
	private void startQuery() {
    	mHandler.cancelOperation(NewsQuery.TOKEN);
        mHandler.startQuery(NewsQuery.TOKEN, null, mNewsUri, NewsQuery.PROJECTION, null, null, NewsQuery.SORT);
    }
	
	private void markRead() {
        final ContentValues values = new ContentValues();
        values.put(News.READ, 1);
		mHandler.startUpdate(-1, null, mNewsUri, values, null, null);
	}
    
    private interface NewsQuery {
    	int TOKEN 	= 0x01;
    	
        String[] PROJECTION = {
                BaseColumns._ID,
                News.NEWS_ID,
                News.CREATED_ON,
                News.TITLE,
                News.ITEM,
        };
        
        String SORT = News.DEFAULT_SORT;

        int _ID 		= 0;
        int NEWS_ID 	= 1;
        int CREATED_ON	= 2;
        int TITLE		= 3;
        int ITEM		= 4;
    }

}
